import ClinicalTrialAccessMethods
import FreebaseAccessFunctions
from xml.dom import minidom

XML_MAPPER_FILE = '../mapping.xml'

def add_CT(CT_ID):
#    res = FreebaseAccessFunctions.freebase_create_new_MT(CT_ID)
    
    MT_guid = FreebaseAccessFunctions.freebase_create_new_topic('/medicine/medical_trial', 'clinicaltrials_identifier', CT_ID)
    print "New Medical Trial created"

    xml_mapper = load_mapping_file(XML_MAPPER_FILE)
    items = xml_mapper.getElementsByTagName('item')

    item_list = get_item_list(items)
    
    for item in item_list:
        process_item(CT_ID, MT_guid, item)
        

#Loads the XML mapping file from disc
def load_mapping_file(filename):
    return minidom.parse(filename) 

#Loads an XML item from the mapping file and converts it to a tuble
#item: An XML item type as described in the mapping.xml file
#return and tuple (array) of the relevant values - note that order matters
def load_from_xmlitem_to_tuple(item):
    res = []
    try:
        res.append(item.getElementsByTagName('insert_type')[0].firstChild.data)
    except:
        print 'No insert_type found'
    
    try:
        res.append(item.getElementsByTagName('src_field')[0].firstChild.data)
    except:
        print 'No src_field found'
    
    try:
        res.append(item.getElementsByTagName('dest_field')[0].firstChild.data)
    except:
        print 'No dest_field found'

    try:
        res.append(item.getElementsByTagName('value_type')[0].firstChild.data)
    except:
        print 'No value_type found'
    
    return res

#Processes an tuple item and stores/links in freebase
#CT_ID: The clinical trial ID
#MT_giud: The medical trial ID
#item: A tuple of values to help get information/store information in freebase
#TODO Stop loading xmldoc every time..should cache it somewhere
def process_item(CT_ID, MT_guid, item):
    if(item[0] == 'link'):
        xmldoc = ClinicalTrialAccessMethods.get_CT(CT_ID)
        try:
            value = xmldoc.getElementsByTagName(item[1])[0].firstChild.data
            id = FreebaseAccessFunctions.freebase_get_id(item[3], 'name', value)
            print id
            #Link the newly created Medical Trial to its design type
            res = FreebaseAccessFunctions.freebase_link_topics(MT_guid, item[2], id)
            print "Linked Medical Trial to Study Design Type"
        except:
            print "study_design '" + value + "' unavailable"
            #Create trial_design_type
            print "Creating new medical_trial_design topic '" + value + "'"
    #        id = FreebaseAccessFunctions.freebase_create_new_topic('/medicine/medical_trial_design', 'name', trial_design_type)
#            print "Created new design at: '" + id + "'"
            
    elif(item[0] == 'text'):
        xmldoc = ClinicalTrialAccessMethods.get_CT(CT_ID)
        #get brief_title
        try:
            brief_title = xmldoc.getElementsByTagName(item[1])[0].firstChild.data
            res = FreebaseAccessFunctions.freebase_add_text_field(MT_guid, item[2], brief_title)
            print "Added title to Medical Trial"
        except:
            print "ERROR: brief_title unavailable"

        return res
#Given an XML formatted list of items returns a list of item tuples
#items: An XML formatted list of items
#return a list of item tuples
def get_item_list(items):
    item_list = []
    for item in items:
        item_list.append(load_from_xmlitem_to_tuple(item))
    return item_list

CT_ID = 'NCT00003900'
add_CT(CT_ID)

id = FreebaseAccessFunctions.freebase_get_id('/medicine/medical_trial_design', 'name', 'Randomized')
print id          
